<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>自制深度学习框架--Relu和Layer | kiloGrand</title><meta name="keywords" content="kuiper_infer"><meta name="author" content="kiloGrand"><meta name="copyright" content="kiloGrand"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="OpType和OperatorOpType采用枚举类enum class，和传统的枚举enum相比，可以降低命名空间的污染、避免发生隐式转换。同时，定义了一个Operator作为父类，其派生类中只存放相关的参数以及修改参数的方法，不包含计算的实现。explicit构造函数是用来防止隐式转换的。 123456789101112131415enum class OpType &amp;#123;  kOper">
<meta property="og:type" content="article">
<meta property="og:title" content="自制深度学习框架--Relu和Layer">
<meta property="og:url" content="https://kilogrand.gitee.io/2023/03/15/kuiper_infer-L4/index.html">
<meta property="og:site_name" content="kiloGrand">
<meta property="og:description" content="OpType和OperatorOpType采用枚举类enum class，和传统的枚举enum相比，可以降低命名空间的污染、避免发生隐式转换。同时，定义了一个Operator作为父类，其派生类中只存放相关的参数以及修改参数的方法，不包含计算的实现。explicit构造函数是用来防止隐式转换的。 123456789101112131415enum class OpType &amp;#123;  kOper">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kilogrand.gitee.io/img/coding.jpg">
<meta property="article:published_time" content="2023-03-15T01:41:10.000Z">
<meta property="article:modified_time" content="2023-03-17T13:07:59.303Z">
<meta property="article:author" content="kiloGrand">
<meta property="article:tag" content="kuiper_infer">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kilogrand.gitee.io/img/coding.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kilogrand.gitee.io/2023/03/15/kuiper_infer-L4/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '自制深度学习框架--Relu和Layer',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-17 21:07:59'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/profile.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/coding.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">kiloGrand</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">自制深度学习框架--Relu和Layer</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-03-15T01:41:10.000Z" title="发表于 2023-03-15 09:41:10">2023-03-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-17T13:07:59.303Z" title="更新于 2023-03-17 21:07:59">2023-03-17</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/">深度学习</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>5分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="自制深度学习框架--Relu和Layer"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="OpType和Operator"><a href="#OpType和Operator" class="headerlink" title="OpType和Operator"></a>OpType和Operator</h2><p>OpType采用枚举类enum class，和传统的枚举enum相比，可以降低命名空间的污染、避免发生隐式转换。<br>同时，定义了一个Operator作为父类，其派生类中只存放相关的参数以及修改参数的方法，不包含计算的实现。<br><a target="_blank" rel="noopener" href="https://zh.cppreference.com/w/cpp/language/explicit">explicit</a>构造函数是用来防止隐式转换的。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">enum class</span> <span class="title class_">OpType</span> &#123;</span><br><span class="line">  kOperatorUnknown = <span class="number">-1</span>,</span><br><span class="line">  kOperatorRelu = <span class="number">0</span>,</span><br><span class="line">  <span class="comment">// 后续添加</span></span><br><span class="line">  <span class="comment">// kOperatorSigmoid = 1,</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Operator</span> &#123;</span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">explicit</span> <span class="title">Operator</span><span class="params">(OpType op_type)</span></span>;</span><br><span class="line">  <span class="keyword">virtual</span> ~<span class="built_in">Operator</span>() = <span class="keyword">default</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  OpType kOpType = OpType::kOperatorUnknown;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="ReluOperator"><a href="#ReluOperator" class="headerlink" title="ReluOperator"></a>ReluOperator</h2><p>ReluOperator参数只有thresh，同时也定义了两个成员函数用来查看和修改thresh。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">ReluOperator</span> : <span class="keyword">public</span> Operator &#123;</span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">explicit</span> <span class="title">ReluOperator</span><span class="params">(<span class="type">float</span> thresh)</span></span>;</span><br><span class="line"></span><br><span class="line">  ~<span class="built_in">ReluOperator</span>() <span class="keyword">override</span> = <span class="keyword">default</span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="type">void</span> <span class="title">set_thresh</span><span class="params">(<span class="type">float</span> thresh)</span></span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="type">float</span> <span class="title">get_thresh</span><span class="params">()</span> <span class="type">const</span></span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span>:</span><br><span class="line">  <span class="type">float</span> thresh_ = <span class="number">0.f</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">ReluOperator::<span class="built_in">ReluOperator</span>(<span class="type">float</span> thresh) : <span class="built_in">thresh_</span>(thresh), <span class="built_in">Operator</span>(OpType::kOperatorRelu) &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">ReluOperator::set_thresh</span><span class="params">(<span class="type">float</span> thresh)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>-&gt;thresh_ = thresh;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">float</span> <span class="title">ReluOperator::get_thresh</span><span class="params">()</span> <span class="type">const</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> thresh_;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Layer"><a href="#Layer" class="headerlink" title="Layer"></a>Layer</h2><p>定义了一个Layer作为父类，其派生类中负责具体计算的实现。<br>其中，Layer的Forwards方法是具体的执行函数，负责将输入的inputs中的数据，进行运算并存放到对应的outputs中。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Layer</span> &#123;</span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">explicit</span> <span class="title">Layer</span><span class="params">(<span class="type">const</span> std::string &amp;layer_name)</span></span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">virtual</span> ~<span class="built_in">Layer</span>() = <span class="keyword">default</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 前向传播</span></span><br><span class="line">  <span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Forwards</span><span class="params">(<span class="type">const</span> std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;inputs,</span></span></span><br><span class="line"><span class="params"><span class="function">                        std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;outputs)</span></span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span>:</span><br><span class="line">  std::string layer_name_;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="ReluLayer"><a href="#ReluLayer" class="headerlink" title="ReluLayer"></a>ReluLayer</h2><p>ReluOperator负责存放计算图中的参数信息，不负责计算，而ReluLayer则负责具体的计算操作，<br>因而，实现了属性存储和运算过程的分离。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">ReluLayer</span> : <span class="keyword">public</span> Layer &#123;</span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">explicit</span> <span class="title">ReluLayer</span><span class="params">(<span class="type">const</span> std::shared_ptr&lt;Operator&gt; &amp;op)</span></span>;</span><br><span class="line"></span><br><span class="line">  ~<span class="built_in">ReluLayer</span>() <span class="keyword">override</span> = <span class="keyword">default</span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="type">void</span> <span class="title">Forwards</span><span class="params">(<span class="type">const</span> std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;inputs,</span></span></span><br><span class="line"><span class="params"><span class="function">                std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;outputs)</span> <span class="keyword">override</span></span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用于注册机制，下一节会介绍</span></span><br><span class="line">  <span class="function"><span class="type">static</span> std::shared_ptr&lt;Layer&gt; <span class="title">CreateInstance</span><span class="params">(<span class="type">const</span> std::shared_ptr&lt;Operator&gt; &amp;op)</span></span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span>:</span><br><span class="line">  <span class="comment">// 存放的参数信息</span></span><br><span class="line">  std::shared_ptr&lt;ReluOperator&gt; op_;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>ReluLayer的构造函数，通过初始化列表<code>:Layer(&quot;Relu&quot;)</code>，调用父类Layer的构造函数来初始化属性<code>layer_name_</code>。</p>
<blockquote>
<p>dynamic_cast是什么意思？ 就是判断一下op指针是不是指向一个relu_op类的指针；<br>这边的op不是ReluOperator类型的指针，就报错；<br>我们这里只接受ReluOperator类型的指针；<br>父类指针必须指向子类ReluOperator类型的指针；<br>op.get()获得 shared_ptr 对象内部包含的普通指针；<br>为什么不讲构造函数设置为const std::shared_ptr<ReluOperator> &amp;op？<br>为了接口统一，具体下节会说到。</p>
</blockquote>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">ReluLayer::<span class="built_in">ReluLayer</span>(<span class="type">const</span> std::shared_ptr&lt;Operator&gt; &amp;op) : <span class="built_in">Layer</span>(<span class="string">&quot;Relu&quot;</span>) &#123;</span><br><span class="line">  <span class="built_in">CHECK</span>(op-&gt;op_type_ == OpType::kOperatorRelu) &lt;&lt; <span class="string">&quot;Operator has a wrong type: &quot;</span> &lt;&lt; <span class="built_in">int</span>(op-&gt;op_type_);</span><br><span class="line">  <span class="comment">// 智能指针 通过op.get()得到普通指针 通过dynamic_cast 转换为ReluOperator *</span></span><br><span class="line">  ReluOperator *relu_op = <span class="built_in">dynamic_cast</span>&lt;ReluOperator *&gt;(op.<span class="built_in">get</span>());</span><br><span class="line">  <span class="built_in">CHECK</span>(relu_op != <span class="literal">nullptr</span>) &lt;&lt; <span class="string">&quot;Relu operator is empty&quot;</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>-&gt;op_ = std::<span class="built_in">make_unique</span>&lt;ReluOperator&gt;(relu_op-&gt;<span class="built_in">get_thresh</span>());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">ReluLayer::Forwards</span><span class="params">(<span class="type">const</span> std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;inputs,</span></span></span><br><span class="line"><span class="params"><span class="function">                         std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;outputs)</span> </span>&#123;</span><br><span class="line">  <span class="built_in">CHECK</span>(<span class="keyword">this</span>-&gt;op_ != <span class="literal">nullptr</span>);</span><br><span class="line">  <span class="built_in">CHECK</span>(<span class="keyword">this</span>-&gt;op_-&gt;op_type_ == OpType::kOperatorRelu);</span><br><span class="line"></span><br><span class="line">  <span class="comment">//一批x，放在vec当中，理解为batchsize数量的tensor，需要进行relu操作</span></span><br><span class="line">  <span class="type">const</span> <span class="type">uint32_t</span> batch_size = inputs.<span class="built_in">size</span>();</span><br><span class="line">  <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; batch_size; ++i) &#123;</span><br><span class="line">    <span class="built_in">CHECK</span>(!inputs.<span class="built_in">at</span>(i)-&gt;<span class="built_in">empty</span>());</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 取出批次当中的一个张量</span></span><br><span class="line">    <span class="type">const</span> std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt; &amp;input_data = inputs.<span class="built_in">at</span>(i);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对张量中的每一个元素进行运算，进行relu运算</span></span><br><span class="line">    input_data-&gt;<span class="built_in">data</span>().<span class="built_in">transform</span>([&amp;](<span class="type">float</span> value) &#123;</span><br><span class="line">      <span class="comment">// 从operator中得到存储的属性</span></span><br><span class="line">      <span class="type">float</span> thresh = op_-&gt;<span class="built_in">get_thresh</span>();</span><br><span class="line">      <span class="keyword">if</span> (value &gt;= thresh) &#123;</span><br><span class="line">        <span class="keyword">return</span> value;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0.f</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 把结果放在outputs中</span></span><br><span class="line">    outputs.<span class="built_in">push_back</span>(input_data);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在Forwards中，首先读取输入input_data, 再对input_data使用armadillo自带的transform，<br>按照我们给定的thresh过滤其中的元素，如果value的值大于thresh则不变，如果小于thresh就返回0。</p>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">TEST</span>(test_layer, forward_relu1) &#123;</span><br><span class="line">  <span class="keyword">using</span> <span class="keyword">namespace</span> kuiper_infer;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 初始化输入，有三个值的一个tensor&lt;float&gt;</span></span><br><span class="line">  std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt; input = std::make_shared&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;(<span class="number">1</span>, <span class="number">1</span>, <span class="number">3</span>);</span><br><span class="line">  input-&gt;<span class="built_in">index</span>(<span class="number">0</span>) = <span class="number">-1.f</span>; <span class="comment">// output对应的应该是0</span></span><br><span class="line">  input-&gt;<span class="built_in">index</span>(<span class="number">1</span>) = <span class="number">-2.f</span>; <span class="comment">// output对应的应该是0</span></span><br><span class="line">  input-&gt;<span class="built_in">index</span>(<span class="number">2</span>) = <span class="number">3.f</span>;  <span class="comment">// output对应的应该是3</span></span><br><span class="line">  std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; inputs; <span class="comment">//作为一个批次去处理</span></span><br><span class="line">  inputs.<span class="built_in">push_back</span>(input);</span><br><span class="line"></span><br><span class="line">  std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; outputs; <span class="comment">//放结果</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 初始化一个relu operator 并设置属性</span></span><br><span class="line">  <span class="type">float</span> thresh = <span class="number">0.f</span>;</span><br><span class="line">  std::shared_ptr&lt;Operator&gt; relu_op = std::<span class="built_in">make_shared</span>&lt;ReluOperator&gt;(thresh);</span><br><span class="line">  <span class="comment">// 初始化 layer</span></span><br><span class="line">  <span class="function">ReluLayer <span class="title">layer</span><span class="params">(relu_op)</span></span>; </span><br><span class="line"></span><br><span class="line">  layer.<span class="built_in">Forwards</span>(inputs, outputs);</span><br><span class="line">  <span class="built_in">ASSERT_EQ</span>(outputs.<span class="built_in">size</span>(), <span class="number">1</span>);  <span class="comment">// 一个批次是1</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; outputs.<span class="built_in">size</span>(); ++i) &#123;</span><br><span class="line">    <span class="built_in">ASSERT_EQ</span>(outputs.<span class="built_in">at</span>(i)-&gt;<span class="built_in">index</span>(<span class="number">0</span>), <span class="number">0.f</span>);</span><br><span class="line">    <span class="built_in">ASSERT_EQ</span>(outputs.<span class="built_in">at</span>(i)-&gt;<span class="built_in">index</span>(<span class="number">1</span>), <span class="number">0.f</span>);</span><br><span class="line">    <span class="built_in">ASSERT_EQ</span>(outputs.<span class="built_in">at</span>(i)-&gt;<span class="built_in">index</span>(<span class="number">2</span>), <span class="number">3.f</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io">kiloGrand</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io/2023/03/15/kuiper_infer-L4/">https://kilogrand.gitee.io/2023/03/15/kuiper_infer-L4/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kilogrand.gitee.io" target="_blank">kiloGrand</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/kuiper-infer/">kuiper_infer</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/03/14/kuiper_infer-L3/"><img class="prev-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">自制深度学习框架--导入数据</div></div></a></div><div class="next-post pull-right"><a href="/2023/03/16/kuiper_infer-L5/"><img class="next-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">自制深度学习框架--框架中的算子注册机制</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-20</div><div class="title">自制深度学习框架--Im2Col原理与卷积层的实现</div></div></a></div><div><a href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-21</div><div class="title">自制深度学习框架--再探Tensor类并构建计算图的图关系</div></div></a></div><div><a href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-24</div><div class="title">自制深度学习框架--实现Yolov5的推理</div></div></a></div><div><a href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-22</div><div class="title">自制深度学习框架--算子的执行流程</div></div></a></div><div><a href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-23</div><div class="title">自制深度学习框架--实现ResNet网络的推理</div></div></a></div><div><a href="/2023/03/14/kuiper_infer-L3/" title="自制深度学习框架--导入数据"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-14</div><div class="title">自制深度学习框架--导入数据</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/profile.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">kiloGrand</div><div class="author-info__description">coder && data-science researcher</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/kiloGrand/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#OpType%E5%92%8COperator"><span class="toc-number">1.</span> <span class="toc-text">OpType和Operator</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ReluOperator"><span class="toc-number">2.</span> <span class="toc-text">ReluOperator</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Layer"><span class="toc-number">3.</span> <span class="toc-text">Layer</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ReluLayer"><span class="toc-number">4.</span> <span class="toc-text">ReluLayer</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-number">5.</span> <span class="toc-text">使用</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理">自制深度学习框架--实现Yolov5的推理</a><time datetime="2023-03-24T12:00:00.000Z" title="发表于 2023-03-24 20:00:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理">自制深度学习框架--实现ResNet网络的推理</a><time datetime="2023-03-23T12:00:00.000Z" title="发表于 2023-03-23 20:00:00">2023-03-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程">自制深度学习框架--算子的执行流程</a><time datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系">自制深度学习框架--再探Tensor类并构建计算图的图关系</a><time datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现">自制深度学习框架--Im2Col原理与卷积层的实现</a><time datetime="2023-03-20T12:00:00.000Z" title="发表于 2023-03-20 20:00:00">2023-03-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By kiloGrand</div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>